#include<ext.h>
#include<ds1302.h>
#include<mcu.h>
void DS1302Reset() {
    DS1302_RESET = 0;
    DS1302_SCLK = 0;
}

uchar DS1302ReadByte() {
    uchar i, temp, res = 0;
    for (i = 0; i < 8; i++) {
        DS1302_SCLK = 1;
        DS1302_SCLK = 0;//下降沿读出DS1302的数据
        temp = DS1302_IO;
        temp <<= 7;
        res >>= 1;
        res |= temp;
    }
    return res;
}

void DS1302WriteByte(uchar d) {
    char i;
    for (i = 0; i < 8; i++) {
        DS1302_IO = (d & 0x01) ? 1 : 0;
        DS1302_SCLK = 0;
        DS1302_SCLK = 1;//上升沿时数据被写入DS1302
        d >>= 1;
    }
}

void DS1302Init() {
    DS1302Reset();
    DS1302WriteByte(0x90);  //涓流充电寄存器
    DS1302WriteByte(0xab);  //允许充电
}

void BcdToDecimal(uchar *date) {
    char i = 0;
    for (i = 0; i < 7; i++) {
        date[i] = date[i] / 16 + date[i] % 16;
    }
}

void DecimalToBcd(uchar *date) {
    char i = 0;
    for (i = 0; i < 7; i++) {
        date[i] = date[i] / 10 * 16 + date[i] % 10;
    }
}

void DS1302Read(uchar *date) {
    char i = 6;
    DS1302Reset();
    DS1302WriteByte(0xBF);       //以多字节方式读取8个字节时钟数据
    date[i--] = DS1302ReadByte();//秒
    date[i--] = DS1302ReadByte();//分
    date[i--] = DS1302ReadByte();//时
    date[i--] = DS1302ReadByte();//星期
    date[i--] = DS1302ReadByte();//月
    date[i--] = DS1302ReadByte();//日
    date[i--] = DS1302ReadByte();//年
    DS1302Reset();
    BcdToDecimal(date);
}

void DS1302Write(uchar *date) {
    char i = 6;
    DecimalToBcd(date);
    DS1302Reset();
    DS1302WriteByte(0x8E);  //写保护寄存器
    DS1302WriteByte(0);     //关写保护
    DS1302Reset();
    DS1302WriteByte(0xBE);     //以多字节方式写入8个字节时钟数据
    DS1302WriteByte(date[i--]);//秒
    DS1302WriteByte(date[i--]);//分
    DS1302WriteByte(date[i--]);//时
    DS1302WriteByte(date[i--]);//星期
    DS1302WriteByte(date[i--]);//月
    DS1302WriteByte(date[i--]);//日
    DS1302WriteByte(date[i--]);//年
    DS1302Reset();
}

